package leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-27 12:46
 **/
public class LeetCode519 {
    int m;
    int n;
    Map<Integer, Integer> map;
    Random random;
    int total;

    public LeetCode519(int m, int n) {
       map = new HashMap<>();
       random = new Random();
       this.m = m;
       this.n = n;
       this.total = m * n;
    }

    public int[] flip() {
       int x = random.nextInt(total);
       total--;
       // 查找位置 x 对应的映射
       int idx = map.getOrDefault(x, x);
       // 将位置 x 对应的映射设置为位置 total 对应的映射
       map.put(x, map.getOrDefault(total, total));
       return new int[]{idx / n, idx % n};
    }

    public void reset() {
        total = m * n;
        map.clear();
    }

    public static void main(String[] args) {
        LeetCode519 code = new LeetCode519(3, 3);
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));
        System.out.println(Arrays.toString(code.flip()));

    }
}
